<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="50%"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '@/components/Form/index';
  import { formSchema } from './menu.data';
  import { BasicDrawer, useDrawerInner } from '@/components/Drawer';
  import { useMessage } from '@/hooks/web/useMessage';
  import { useI18n } from '@/hooks/web/useI18n';
  import { GetAllMenu,UpdateMenu,AddMenu } from '@/api/system/menu';
  const { notification, createErrorModal } = useMessage();
  const { t } = useI18n();
  export default defineComponent({
    name: 'MenuDrawer',
    components: { BasicDrawer, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      var update = Object.create(null)
      const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
        labelWidth: 100,
        schemas: formSchema,
        showActionButtonGroup: false,
        baseColProps: { lg: 12, md: 24 },
      });

      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        resetFields();
        setDrawerProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;

        if (unref(isUpdate)) {
          setFieldsValue({
            ...data.record,
          });
        }
        update = data.record
        const treeapidata = await GetAllMenu({});
        const par_menu = {
          id:'0',
          key:'0',
          label:'最上级',
          menuName:'最上级',
          name:'最上级',
          parentId: "0",
          value: "0"
        }
        treeapidata.data.push(par_menu)
        let treeData = treeapidata.data
        await updateSchema({
          field: 'parentMenu',
          componentProps: { treeData },
        });
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增菜单' : '编辑菜单'));

      async function handleSubmit() {
        try {
          const values = await validate();
          setDrawerProps({ confirmLoading: true });
            let update_value = {}
              update_value['name'] = values.menuName
             update_value['parentId'] = values.parentMenu
             update_value['type'] = parseInt(values.type)
             update_value['orderNum'] = values.orderNo
             update_value['icon'] = values.icon ==undefined?'':values.icon
             update_value['state'] = parseInt(values.status)
             update_value['permission'] = values.permission == undefined ? '' : values.permission
             update_value['method'] =  values.method == undefined ? '' : values.method
             update_value['redirect'] = values.redirect == undefined? '' :values.redirect
             update_value['currentActiveMenu'] = values.currentActiveMenu == undefined? '' :values.currentActiveMenu
             update_value['realPath'] = values.realPath == undefined? '' :values.realPath
             update_value['component'] = values.type == 0?'LAYOUT' :values.component==undefined?'':values.component
              update_value['path'] = values.path == undefined?'':values.path
              update_value['isExt'] = parseInt(values.isExt == undefined?0:values.isExt)
              update_value['isShow'] = parseInt(values.show == undefined ? 1: values.show)
              update_value['code'] =  values.code == undefined ? '' : values.code
              update_value['carryParam'] = parseInt(values.carryParam == undefined ? 0: values.carryParam)
              update_value['tenantIsOpen'] = parseInt(values.tenantIsOpen == undefined ? 0: values.tenantIsOpen)
          if (unref(isUpdate)) {
             update_value['id'] = update.id
             const update_menu = await UpdateMenu(update_value)
             if(update_menu.code == 200){
                closeDrawer();
                notification.success({
                message: t('sys.update.success'),
                description: t('sys.update.success'),
                duration: 3,
              });

                emit('success');
             }else{
                notification.error({
                message: t('sys.update.error'),
                description: update_menu.msg,
                duration: 3,
              });
             }
            //  组装update数据
          }else{
            // 调用添加菜单接口
              setDrawerProps({ confirmLoading: true });
              const update_menu = await AddMenu(update_value)
             if(update_menu.code == 200){
                closeDrawer();
                notification.success({
                message: t('sys.add.addsuccess'),
                description: t('sys.add.addsuccess'),
                duration: 3,
              });
                emit('success');
             }else{
                notification.error({
                message: t('sys.add.addfail'),
                description: update_menu.msg,
                duration: 3,
              });
             }
          }
          // TODO custom api
        } finally {
          setDrawerProps({ confirmLoading: false });
        }
      }

      return { registerDrawer, registerForm, getTitle, handleSubmit };
    },
  });
</script>
